/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.kobakei.utils;

import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.app.Context;
import ohos.utils.net.Uri;

/**
 * BrowserIntents
 *
 * @since 2021-05-25
 */
public class BrowserIntents {
    private Context context;
    private Intent intent;

    private BrowserIntents(Context context) {
        this.context = context;
    }

    /**
     * BrowserIntents
     *
     * @param context
     * @return BrowserIntents
     */
    public static BrowserIntents from(Context context) {
        return new BrowserIntents(context);
    }

    /**
     * BrowserIntents
     *
     * @return BrowserIntents
     */
    public BrowserIntents openBrowser() {
        intent = new Intent();
        intent.setAction("android.intent.action.VIEW");
        intent.setUri(Uri.parse("about:blank"));
        intent.addFlags(Intent.FLAG_ABILITY_NEW_MISSION);
        return this;
    }

    /**
     * BrowserIntents
     *
     * @param url
     * @return BrowserIntents
     */
    public BrowserIntents openLink(String url) {
        // if protocol isn't defined use http by default
        if (!url.isEmpty() && !url.contains("://")) {
            url = "http://" + url;
        }

        intent = new Intent();
        intent.setAction("android.intent.action.VIEW");
        intent.setUri(Uri.parse(url));
        return this;
    }

    /**
     * BrowserIntents
     *
     * @param uri
     * @return BrowserIntents
     */
    public BrowserIntents openLink(Uri uri) {
        return openLink(uri.toString());
    }

    /**
     * BrowserIntents
     *
     * @return BrowserIntents
     */
    public BrowserIntents openBaidu() {
        Uri uri = Uri.parse("https://Baidu.com");
        intent = new Intent();
        intent.setAction("android.intent.action.VIEW");
        intent.setUri(uri);
        return this;
    }

    /**
     * BrowserIntents
     *
     * @return Intent
     */
    public Intent build() {
        return intent;
    }

    /**
     * startAbility
     *
     * @param intent
     */
    private void startAbility(Intent intent) {
        if (!(context instanceof Ability)) {
            intent.addFlags(Intent.FLAG_ABILITY_NEW_MISSION);
        }
        context.startAbility(intent, 0);
    }

    /**
     * show
     */
    public void show() {
        startAbility(build());
    }
}
